<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';

const title = "后端->前端 无参 原生 WebSocket"

const messages = ref([]);
let socket = null;

// STOMP 协议工具函数
const createStompFrame = (command, headers, body) => {
  let frame = `${command}\n`;
  for (const [key, value] of Object.entries(headers)) {
    frame += `${key}:${value}\n`;
  }
  frame += `\n${body || ''}\x00`;
  return frame;
};

onMounted(() => {
  // 1. 创建 WebSocket 连接（假设后端地址为 ws://localhost:8080/ws）
  socket = new WebSocket("ws://localhost:8080/ws");

  // 2. 连接成功后发送 STOMP CONNECT 帧
  socket.onopen = () => {
    console.log("onopen----")
    const connectFrame = createStompFrame('CONNECT', {
      'accept-version': '1.1,1.0',
      'heart-beat': '10000,10000'
    });
    console.log(connectFrame)
    socket.send(connectFrame);
  };

  // 3. 处理接收到的消息（需解析 STOMP 帧）
  socket.onmessage = (event) => {
    console.log("onmessage----")
    const data = event.data;
    if (data.startsWith('CONNECTED')) {
      // 连接成功，订阅目标主题
      const subscribeFrame = createStompFrame('SUBSCRIBE', {
        id: 'sub-0',
        destination: '/topic/time-alerts'
      });
      socket.send(subscribeFrame);
    } else if (data.startsWith('MESSAGE')) {
      // 提取消息体（假设消息为 JSON）
      const body = data.match(/\n\n(.*)\x00/)[1];
      const parsedData = JSON.parse(body);
      messages.value.push(parsedData);
    }
  };

  socket.onclose = () => {
    console.log('WebSocket 连接关闭');
  };
});

onBeforeUnmount(() => {
  if (socket) socket.close();
});
</script>


<template>
  <h2>{{title}}</h2>
  <ul>
    <li v-for="msg in messages" :key="msg.id">
      {{ msg.id }} - {{ msg.time }}
    </li>
  </ul>
  <hr/>
</template>

